<?php
/**
 * Create By: PhpStorm
 * User: yuanxuncheng
 * File: Logout.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\user;

use app\api\model\dao\Picture;
use app\api\model\dao\TaskLog;
use app\api\model\dao\UserAccount;
use app\api\model\dao\UserCurrency;
use think\Exception;
use app\library\Error;
use app\library\PageBase;
use think\Validate;
use think\Cache;
use think\Log;
use app\library\aliyun\oss\OssWorker;
use app\library\aliyun\sts\StsWorker;
use app\library\Flag;


class UpdateUserLabel extends PageBase
{

    private $objUserAccount;
    private $objOss;
    private $objPicture;
    private $objTaskLog;
    private $objUserCurrency;


    public function __construct()
    {
        parent::__construct();

        $this->objUserAccount = new UserAccount();
        $this->objOss = new OssWorker();
        $this->objPicture = new Picture();
        $this->objTaskLog = new TaskLog();
        $this->objUserCurrency = new UserCurrency();

    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'label' => 'require',
        ];
        $msg = [
            'label.require' => '请添加标签',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function excute($param)
    {
        $ret = $this->checkToken($param);
        if (false === $ret) {
            return $this->getRes(Error::ERR_NO_AUTH);
        }

        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            Log::error(__METHOD__ . ' param: ' . json_encode($param));
            return $this->getRes(Error::ERR_PARAM);
        }

        $label_color_count = count(Flag::$label_color);

        if (1 == $label_color_count) {
            $color = Flag::$label_color[0];
        } else if (0 < $label_color_count) {
            $color = Flag::$label_color[mt_rand(0, $label_color_count - 1)];
        } else {
            $color = '#272727';
        }

        $this->label[] = ['title' => $param['label'], 'color' => $color];

        $input = [
            'user_id' => $this->user_id,
            'label' => $this->label
        ];

        $ret = $this->objUserAccount->updateUserAccount($input);
        if (false === $ret) {
            Log::error(__METHOD__ . ' update user label fail.[' . json_encode($input) . ']');
            return $this->getRes(Error::ERR_SYS);
        }

        $this->data = $input;

        return $this->getRes();
    }
}
